package com.dhemery.mack.actions;

import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.ui.IWorkbenchPage;

import com.dhemery.mack.adapters.EditorLauncher;
import com.dhemery.mack.adapters.ImageDescriptorSource;
import com.dhemery.mack.model.Folder;
import com.dhemery.mack.model.Node;

public abstract class AddNodeAction extends ExplorerViewAction {

	protected abstract Node makeNewNode();

	public AddNodeAction(String name, String id, String imagePath, IWorkbenchPage page, TreeViewer viewer, IAdapterFactory factory, ImageDescriptorSource imageDescriptorSource) {
		super(name, id, imagePath, page, viewer, factory, imageDescriptorSource);
}

	@Override
	public void execute(IWorkbenchPage page, IAdapterFactory factory, Object[] selectedObjects) {
		Node newNode = makeNewNode();
		Folder parentFolder = (Folder)selectedObjects[0];
		parentFolder.addNode(newNode);
		EditorLauncher launcher = new EditorLauncher(page, factory);
		launcher.edit(newNode);
	}

	private boolean isOneFolder(Object[] objects) {
		return hasOneObject(objects) && firstIsFolder(objects);
	}

	private boolean firstIsFolder(Object[] objects) {
		return objects[0] instanceof Folder;
	}

	private boolean hasOneObject(Object[] objects) {
		return objects.length == 1;
	}

	@Override
	protected boolean isSelected(Object[] selectedObjects) {
		return isOneFolder(selectedObjects);
	}

}